const storageOptions = {
	namespace: 'sheepcity_', // key的前缀
}

/**
 * 设置本地缓存
 * @param {string} key 
 * @param {any} value 
 * @param {number} expire 
 * @return {void}
*/
function setStorage(key: string, value: any, expire?: number): void {
	let time: number | null = null;
	if (expire) {
		time = new Date().getTime() + expire;
	}
	const data = { value, expire: time };
	uni.setStorageSync(`${storageOptions.namespace}${key}`, data);
}

/**
 * 获取本地缓存
 * @param {string} key 
 * @return {any}
*/
function getStorage(key: string): any {
	const storage = uni.getStorageSync(`${storageOptions.namespace}${key}`);
	const { value, expire } = storage;
	const currentTime = new Date().getTime();
	// 如果本地储存有设置时间，并且当前时间大于储存时间，清除本地储存信息
	if (expire && expire < currentTime) {
		removeStorage(key);
		return null;
	}
	return value || null;
}

/**
 * 清除本地缓存
 * @param {string} key 
 * @return {void}
*/
function removeStorage(key: string): void {
	uni.removeStorageSync(`${storageOptions.namespace}${key}`);
}

/* 清除所有本地缓存 */
function clearStorage(): void {
	const { keys } = uni.getStorageInfoSync();
	keys.forEach((key: string) => {
		if (key.includes(storageOptions.namespace)) {
			removeStorage(key.replace(storageOptions.namespace, ''));
		}
	});
}

export default {
	get: getStorage,
	set: setStorage,
	remove: removeStorage,
	clear: clearStorage,
}